package cn.kgc.vue.service.impl;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.util.IdUtil;
import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.vo.TemplateVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.vue.entity.Template;
import cn.kgc.vue.service.TemplateService;
import cn.kgc.vue.mapper.TemplateMapper;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.List;

/**
* @author 11839
* @description 针对表【sys_template】的数据库操作Service实现
* @createDate 2024-06-28 15:23:44
*/
@Service
public class TemplateServiceImpl extends ServiceImpl<TemplateMapper, Template>
    implements TemplateService{

    @Override
    public ResponseResult resourcesPage(QueryCondition<Template> queryCondition) {
        Page<Template> templatePage = new Page<>(queryCondition.getPage(), queryCondition.getLimit());

        String fileName = queryCondition.getSearchParams().getFileName();

        LambdaQueryWrapper<Template> lambda = new QueryWrapper<Template>().lambda();
        lambda.eq(StringUtils.isNotBlank(fileName), Template::getFileName, fileName)
                .orderByDesc(Template::getCreateTime);

        baseMapper.selectPage(templatePage, lambda);
        long total = templatePage.getTotal();
        List<Template> list = templatePage.getRecords();

        return ResponseResult.success().data("total", total).data("tableData", list);
    }

    @Override
        public ResponseResult upload (MultipartFile file){
            if (file.isEmpty()) {
                return ResponseResult.fail().message("请选择文件");
            }

            // 处理文件的名字  唯一
            String originalFilename = file.getOriginalFilename();
            // 获取文件大小
            double size1 = file.getSize() / 1024.0;
            //保留两位小数

                 String  str = String.format("%.2f",size1);
                 double size = Double.parseDouble(str);

            // 获取文件的扩展名
            String filenameExtension = org.springframework.util.StringUtils.getFilenameExtension(originalFilename);
            String uuid = IdUtil.simpleUUID();
            String uuidName = uuid + "." + filenameExtension;

            try {
                byte[] fileContent = file.getBytes();
                String base64File = Base64Utils.encodeToString(fileContent);
                return ResponseResult.success()
                        .data("uuidName", uuidName)
                        .data("size", size)
                        .data("fileContent", base64File).message("文件上传成功");
            } catch (IOException e) {
                return ResponseResult.fail().message("文件上传失败");
            }
        }

    @Override
    public ResponseResult addResourcesInfo(TemplateVO templateVO) {
        if (templateVO.getFileContent()==null){
            return ResponseResult.fail().message("请传入文件");
        }
        //先将文件写入文件夹中 然后再将数据写入数据库中
        // Base64 字符串
        String base64File =templateVO.getFileContent();

        // 解码 Base64 字符串
        byte[] fileContent = Base64.getDecoder().decode(base64File);

        // 指定输出文件夹路径和文件名
        String folderPath = "/usr/java/download/";
        String fileName = templateVO.getUuidName();

        // 创建文件夹
        File folder = new File(folderPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        // 指定文件路径
        File file = new File(folder, fileName);

        // 将字节数组写入文件
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(fileContent);
        } catch (IOException e) {
            e.printStackTrace();
        }



        Template template = new Template();
        template.setSize(templateVO.getSize());
        template.setFileName(templateVO.getFileName());
        template.setFileType(templateVO.getFileType());
        template.setUuidName(templateVO.getUuidName());

         baseMapper.insert(template);

        return ResponseResult.success().message("上传成功");
    }

    @Override
    public ResponseResult deleteResources(String id) {
        //通过id查出 uuidname  然后到指定磁盘删除
        //然后再删除数据库中的数据
        Template template = baseMapper.selectById(id);
        String uuidName = template.getUuidName();

        // 删除资源信息
        LambdaQueryWrapper<Template> lambda = new QueryWrapper<Template>().lambda();
        lambda.eq(Template::getUuidName, uuidName);
        baseMapper.delete(lambda);
        // 删除文件资源
        File file = new File("/usr/java/download/" + uuidName);
        file.delete();

        return ResponseResult.success().message("删除成功");

    }

    @Override
    public ResponseResult download(HttpServletResponse response, String uuid) {
      //拿着uuid去指定文件夹下下载

        File file = new File("/usr/java/download/" + uuid);
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.copy(fileInputStream,outputStream);
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

}




